import {reqArticleTable,reqArticlestatus,reqartall} from '../../api/information'
Page({
    data: {
      iaem: [],
      num:'',
      ymy:true,
      token:'',
      user:{},
  
    },
  //文章查询
async reqArticleTable(type, user_id) {
  let id='';
  if(type==0){
      id=1
  }else{
    id=user_id
  }
  const art = await reqArticleTable(type, id);
  if(art.data.articleall==null || art.data.articleall==''){
    this.setData({
        ymy:false
    })
  }
  this.setData({ iaem: art.data.articleall });
  return art.data.articleall; 
},
  //查看详情
  xq(e){
    wx.navigateTo({
      url: '/pages/information/particulars/particulars?articleid='+e.currentTarget.dataset.num
    })
  },
  //查看是否收藏
  async reqArticlestatus(articles) {
    const userid =wx.getStorageSync('userInfo').userId;
    const status = await reqArticlestatus(userid);
    // 直接使用传入的 articles，保证数据最新
    const updatedItems = articles.map(item => ({
      ...item,
      collected: status.data.articlestatus.includes(item.articleTableId)
    }));
    this.setData({ iaem: updatedItems });
  },
  onusers(){
    const userInfo=wx.getStorageSync('userInfo');
    const token=wx.getStorageSync('token')
    if(token!=null){
      this.setData({
        user:userInfo,
        token
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */

  async onLoad(options) {
    this.onusers()
    try {
      const articles = await this.reqArticleTable(options.type, this.data.user.userId);
      if(wx.getStorageSync('userInfo').userId==null || wx.getStorageSync('userInfo').userId==''){
        return;
      }else{
        await this.reqArticlestatus(articles);
      }
    } catch (error) {
      console.error('加载失败:', error);
    }
  },
    // 切换收藏状态
    toggleCollect(e) {
      if(wx.getStorageSync('userInfo').userId==null || wx.getStorageSync('userInfo').userId==''){
        wx.showToast({
          title: '登录后即可收藏',
          icon:'error'
        })
        return;
    
      }else{
      const index = e.currentTarget.dataset.index;  // 获取点击的索引
      const updatedIaem = this.data.iaem;

      // 切换收藏状态
      updatedIaem[index].collected = !updatedIaem[index].collected;

      reqartall(this.data.user.userId, updatedIaem[index].articleTableId).then(result => {
    wx.showToast({
      title: result.msg,
    })
  });
      // 更新 data
      this.setData({
        iaem: updatedIaem
      });
    }
  }
  })
  